package cn.edu.sdjzu.xg.kcsj.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "F02_EncodingFilter",urlPatterns = {"/*"})
public class EncodingFilter implements Filter {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(EncodingFilter.class);

    @Override
    public void init(FilterConfig config) throws ServletException{

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws ServletException, IOException{
       log.debug("EncodingFilter begins");
        // HttpServletRequest是ServletRequest的子接口
        HttpServletRequest request =(HttpServletRequest) req;
        HttpServletResponse response =(HttpServletResponse) resp;
            response.setContentType("application/json;charset=UTF-8");
            String method = request.getMethod();
            // contains区分大小写
            if(!"DELETE".contains(method)){
                request.setCharacterEncoding("UTF-8");
            }
        chain.doFilter(req,resp);
        log.debug("EncodingFilter ends");
    }

    @Override
    public void destroy() {
    }
}
